import cv2 as cv
face_detector=cv.CascadeClassifier(cv.data.haarcascades+"haarcascade_frontalface_alt2.xml")
eye_detector=cv.CascadeClassifier(cv.data.haarcascades+"haarcascade_eye.xml")
smile_detector=cv.CascadeClassifier(cv.data.haarcascades+"haarcascade_smile.xml")


cap = cv.VideoCapture(0)
# image=cv.imread('people.jpg')
while True:
    # 读取摄像头的帧
    ret, frame = cap.read()
    if not ret:
        break
    faces=face_detector.detectMultiScale(frame,scaleFactor=1.05,minNeighbors=3,
                                        minSize=(50,50),maxSize=(300,300))
    for x,y,width,height in faces:
        cv.rectangle(frame,(x,y),(x+width,y+height),(0,0,255),2,cv.LINE_8,0)

        roi=frame[y:y+height,x:x+width]
        eyes=eye_detector.detectMultiScale(roi,scaleFactor=1.1,minNeighbors=5,
                                        minSize=(20,20),maxSize=(30,30))
        smiles=smile_detector.detectMultiScale(roi,scaleFactor=1.05,minNeighbors=2,
                                                minSize=(20,20))
        for ex,ey,ew,eh in eyes:
            cv.rectangle(roi,(ex,ey),(ex+ew,ey+eh),(255,0,0),2)

        for sx,sy,sw,sh in smiles:
            cv.rectangle(roi,(sx,sy),(sx+sw,sy+sh),(0,255,0),2)
            cv.putText(frame,'Smile',(x+10,y-7),cv.FONT_HERSHEY_SIMPLEX,0.8,(0,255,0),2)


    cv.imshow("faces", frame)
        
    # 按下 'q' 键退出循环
    if cv.waitKey(1) & 0xFF == ord('q'):
        break
    
cap.release()
cv.destroyAllWindows()
